package com.dmooo.ymx.activity;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.design.widget.TextInputEditText;
import android.text.Editable;
import android.text.Html;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.baichuan.trade.biz.login.AlibcLogin;
import com.alibaba.baichuan.trade.biz.login.AlibcLoginCallback;
import com.bumptech.glide.Glide;
import com.dmooo.ymx.R;
import com.dmooo.ymx.base.BaseActivity;
import com.dmooo.ymx.bean.AccPass;
import com.dmooo.ymx.bean.PddClient;
import com.dmooo.ymx.bean.Response;
import com.dmooo.ymx.bean.UserInfoBean;
import com.dmooo.ymx.bean.VersionInformationBean;
import com.dmooo.ymx.common.ACache;
import com.dmooo.ymx.common.CommonUtils;
import com.dmooo.ymx.common.LogUtils;
import com.dmooo.ymx.common.SPUtils;
import com.dmooo.ymx.common.T;
import com.dmooo.ymx.config.Constants;
import com.dmooo.ymx.https.HttpUtils;
import com.dmooo.ymx.https.onOKJsonHttpResponseHandler;
import com.dmooo.ymx.login.LoginActivity;
import com.dmooo.ymx.login.WelActivity;
import com.dmooo.ymx.mall.AddressActivity;
import com.dmooo.ymx.mall.MyShopMallActivity;
import com.dmooo.ymx.merchantbean.MyMerchantlistbean;
import com.dmooo.ymx.my.MyInformationActivity;
import com.dmooo.ymx.my.ResetPasswordActivity;
import com.dmooo.ymx.my.ResetPhoneActivity;
import com.dmooo.ymx.utils.APKVersionCodeUtils;
import com.dmooo.ymx.utils.CleanMessageUtil;
import com.dmooo.ymx.utils.ListDataSave;
import com.dmooo.ymx.utils.TypeConvertUtil;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.hyphenate.EMCallBack;
import com.hyphenate.chat.EMClient;
import com.lljjcoder.style.citylist.Toast.ToastUtils;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;
import com.loopj.android.http.TextHttpResponseHandler;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cz.msebera.android.httpclient.Header;
import me.drakeet.materialdialog.MaterialDialog;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;

/**
 * @author wim
 * 设置页
 */
public class SetActivity extends BaseActivity {
    @BindView(R.id.tv_left)
    TextView tvLeft;
    @BindView(R.id.tv_title)
    TextView tvTitle;
    @BindView(R.id.tv_tb)
    TextView tvTb;
    @BindView(R.id.tv_chat)
    TextView tvchat;
    @BindView(R.id.tv_address)
    TextView tv_address;
    @BindView(R.id.finishEdit)
    TextView finishEdit;
    @BindView(R.id.logingName)
    TextInputEditText logingName;
    private ACache mAcache;
    private String token;
    private MaterialDialog downDilog;
    private View downLayout;
    private ProgressBar downProgressBar;
    private UpdateService.Builder builder;
    private boolean isDownLoadFinish = false;
    private AlibcLogin alibcLogin;
    private boolean isEditIng=false;
    private UserInfoBean userBean;

    private SharedPreferences mPref;
    private SharedPreferences.Editor mEditor;

    List<AccPass> classTests=new ArrayList<>();

    ListDataSave dataSave;
    public static Activity activity;


    @Override
    protected void initUI() {
        setContentView(R.layout.activity_set);
        ButterKnife.bind(this);
        mMaterialDialog = new MaterialDialog(this);//初始化MaterialDialog
        downDilog = new MaterialDialog(this);
        downLayout = LayoutInflater.from(this).inflate(R.layout.down_layout, null);
        downProgressBar = downLayout.findViewById(R.id.pb_progressbar);
        downDilog.setView(downLayout);
        downDilog.setCanceledOnTouchOutside(false);
        dataSave = new ListDataSave(SetActivity.this, "baiyu");

        mPref = getSharedPreferences("login", MODE_PRIVATE);
        activity = this;
    }

    @Override
    protected void initData() {
        tvLeft.setVisibility(View.VISIBLE);
        tvTitle.setText("设置");
        mAcache = ACache.get(this);
        token = SPUtils.getStringData(this,"token","");
        tvTb.setTag("0");
        alibcLogin = AlibcLogin.getInstance();
        getUserMsg();
        whetherBindingTaobao();
    }

    private void loginHuanxin() {
        try{
            EMClient.getInstance().login(""+SPUtils.getStringData(SetActivity.this, "uid", ""), "123456", new EMCallBack() {//回调
                @Override
                public void onSuccess() {
                    EMClient.getInstance().groupManager().loadAllGroups();
                    EMClient.getInstance().chatManager().loadAllConversations();
                    Log.d("main", "登录聊天服务器成功！");
                    SPUtils.put(SetActivity.this, "new", "1");
//                    finish();
                }

                @Override
                public void onProgress(int progress, String status) {

                }

                @Override
                public void onError(int code, String message) {
                    if(message.contains("already login")){
                        EMClient.getInstance().logout(true);
                    }else{
//                    handler.sendEmptyMessage(0);
                    }
                    Log.d("main", "登录聊天服务器失败！" + code+"  "+message);
                }
            });
        }catch (Exception e){
            e.printStackTrace();
        }

    }


    @Override
    protected void initListener() {

    }
    private void whetherBindingTaobao() {
        String url = Constants.WHETHER_BINDING_TAOBAO;
        OkHttpClient okHttpClient = new OkHttpClient();
        RequestBody body = new FormBody.Builder().add("token", token).build();
        Request request = new Request.Builder().url(url).post(body).build();
        Call call = okHttpClient.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                e.printStackTrace();
            }

            @Override
            public void onResponse(Call call, okhttp3.Response response) throws IOException {
                String result = response.body().string();
                try {
                    JSONObject jsonObject = new JSONObject(result);
                    String code = jsonObject.getString("code");
                    JSONObject jsonData = jsonObject.getJSONObject("data");
                    String isBinding = jsonData.optString("is_binding");
                    if ("Y".equals(isBinding)) {
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                tvTb.setText("淘宝号解绑");
                                tvTb.setTag("1");
                            }
                        });
                    } else {
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }

            }
        });
    }
    @OnClick({R.id.txt_w,R.id.txt_q,R.id.tv_tb,R.id.tv_left, R.id.tv_seven, R.id.tv_eight,R.id.tv_ten, R.id.tv_phone, R.id.tv_zfb,R.id.tv_chat,R.id.logingName
    ,R.id.tv_address,R.id.finishEdit,R.id.tv_change})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.txt_w:
                NewsActivity.actionStart(this,"48", "隐私政策");
                break;
            case R.id.txt_q:
                NewsActivity.actionStart(this,"1", "用户协议");
                break;
            case R.id.tv_left:
                finish();
                break;
            case R.id.tv_tb:
                if("1".equals(tvTb.getTag().toString())){
                    //解绑操作
                    AlertDialog.Builder builder = new AlertDialog.Builder(this);
                    builder.setTitle("源曦默");
                    builder.setMessage("您确定要解绑淘宝账号吗？解除后购买的淘宝订单将得不到返利，若淘宝账号绑定错误需要进行换绑可进行此操作。");
                    builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.dismiss();
                        }
                    });
                    builder.setPositiveButton("确定解绑", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            unBindTb();
                            dialog.dismiss();
                        }
                    });
                    builder.show();
                }else{
                    //绑定操作
                    AlertDialog.Builder builder = new AlertDialog.Builder(this);
                    builder.setTitle("源曦默");
                    builder.setMessage("一个源曦默账号只可绑定一个淘宝账号，通过绑定的淘宝账号购物可得到返利，其他淘宝账号无法获得返利\n");
                    builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.dismiss();
                        }
                    });
                    builder.setPositiveButton("知道了", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            bingTb();
                            dialog.dismiss();
                        }
                    });
                    builder.show();
                }
                break;
            case R.id.tv_zfb:
                openActivity(BindActivity.class);
                break;
            case R.id.tv_seven:
                openActivity(ResetPasswordActivity.class);
                break;
            case R.id.tv_phone:
                openActivity(ResetPhoneActivity.class);
                break;
            case R.id.tv_eight:
                try {
                    showClearDialog();
                } catch (Exception e) {
                    e.printStackTrace();
                }
                break;
            case R.id.tv_ten:
                getData();
                break;
            case R.id.tv_chat:
//                Bundle bundle=new Bundle();
//                bundle.putString("name","平台客服");
//                bundle.putString("uuid","kf_3");
//                bundle.putString("image","");
//                bundle.putString("msg",getIntent().getExtras().getString("msg"));
//                openActivity(ChatActivity.class,bundle);
                Bundle bundle=new Bundle();
                try{
                    bundle.putString("merchant_id",merchantlistbeans.get(0).merchant_id);
                }catch (Exception e){
                    e.printStackTrace();
                }
                bundle.putString("type","2");
                bundle.putString("image","");
                bundle.putString("msg","你好，我想咨询服务:");
                openActivity(MerchantAdminListActivity.class,bundle);
                break;
            case R.id.finishEdit:
                    AlertDialog alertDialog = new AlertDialog.Builder(SetActivity.this)
                            .setTitle("提示")
                            .setCancelable(false)
                            .setMessage("是否设置该会员名，只能编辑一次哦")
                            .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    dialog.cancel();
                                }
                            })
                            .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    dialog.cancel();
//                                    showToast("调用接口");
                                    if(!"".equals(logingName.getText().toString())){
                                        setUsername();
                                    }
                                }
                            })
                            .create();
                    alertDialog.show();
                    alertDialog.getButton(DialogInterface.BUTTON_NEGATIVE).setTextColor(Color.BLACK);
                    alertDialog.getButton(AlertDialog.BUTTON_POSITIVE).setTextColor(getResources().getColor(R.color.colorPrimary));
                break;
            case R.id.tv_address:
                openActivity(AddressActivity.class);
                break;
            case R.id.tv_change:
//                getData();
                openActivity(ChangeAccountActivity.class);
//                Toast.makeText(SetActivity.this, dataSave.getDataList("javaBean").toString(), Toast.LENGTH_SHORT).show();
//                classTests = getDataList("login");
//                if (classTests.size() > 0) {
//                    for(int i=0;i<classTests.size();i++){
//                        Log.e("AYD", classTests.size() + "");
//                        Log.e("AYD", classTests.get(i).getAccount()+ "");ww
//                    }
//                    et_id.setText(classTests.get(classTests.size() - 1).getAccount());
//                    et_pwd.setText(classTests.get(classTests.size() - 1).getPassword());
//                }
                break;
        }
    }

    /**
     * 获取List
     *
     * @param tag
     * @return
     */
    public List<AccPass> getDataList(String tag) {
        List<AccPass> datalist = new ArrayList<>();
        String strJson = mPref.getString(tag, null);
        if (null == strJson) {
            return datalist;
        }
        Gson gson = new Gson();
        datalist = gson.fromJson(strJson, new TypeToken<List<AccPass>>() {
        }.getType());
        return datalist;

    }

    /**
     * 获取商户列表  源曦默官方旗舰店
     */
    public List<MyMerchantlistbean> merchantlistbeans = new ArrayList<>();
    private void getmerchantlist() {
        RequestParams requestParams = new RequestParams();
        HttpUtils.post(Constants.getMerchantList, requestParams, new TextHttpResponseHandler() {
            @Override
            public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
                Log.d("dsfasd", responseString);
            }
            @Override
            public void onSuccess(int statusCode, Header[] headers, String responseString) {
                try {
                    JSONObject object = new JSONObject(responseString);
                    if ("0".equals(object.getString("code"))) {
                        JSONArray array = object.getJSONObject("data").getJSONArray("list");
                        merchantlistbeans.clear();
                        for (int i = 0; i < array.length(); i++) {
                            merchantlistbeans.add(new Gson().fromJson(array.getJSONObject(i).toString(), MyMerchantlistbean.class));
                        }
                    } else {
                        showToast(object.getString("msg"));
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });
    }



    private void unBindTb(){
        RequestParams params = new RequestParams();
        params.put("token", token);
        // get方式
        HttpUtils.post(Constants.UNBING_TAOBAO, params, new AsyncHttpResponseHandler() {
            @Override
            public void onStart() {
                // 显示进度条
                super.onStart();
                showLoadingDialog();
            }

            @Override
            public void onSuccess(int arg0, Header[] arg1, byte[] arg2) {
                String responseResult = new String(arg2);
                LogUtils.e(TAG, "onSuccess()--" + responseResult);
                try {
                    JSONObject jsonObject = new JSONObject(responseResult);
                    String code = jsonObject.optString("code");
                    String msg = jsonObject.optString("msg");
                    // String result = jsonObject.optString("result");
                    if ("0".equalsIgnoreCase(code)) { // 操作成功
                        showToast("解绑成功");
                        unbindLd();
                        tvTb.setTag("0");
                        tvTb.setText("绑定淘宝号");
                        alibcLogin.logout(new AlibcLoginCallback() {
                            @Override
                            public void onSuccess(int i, String s, String s1) {

                            }

                            @Override
                            public void onFailure(int i, String s) {

                            }
                        });
                    } else {
                        showToast(msg);
                    }
                } catch (JSONException e) {
                    LogUtils.i(TAG, e.toString());
                }
            }

            @Override
            public void onFinish() {
                // 隐藏进度条
                super.onFinish();
                closeLoadingDialog();
            }

            @Override
            public void onFailure(int arg0, Header[] arg1, byte[] arg2, Throwable arg3) {
            }
        });
    }
    private void bingTb(){
        //如果未绑定
        alibcLogin.showLogin( new AlibcLoginCallback() {
            @Override
            public void onSuccess(int i, String s, String s1) {
                s=alibcLogin.getSession().userid;
                if (s == null) {
                    return;
                }
                int length = s.length();
                if (length > 6) {
                    String b = s.substring(length - 6, length);
                    String[] bArr = b.split("");
                    String c = bArr[1] + "" + bArr[2] + "" + bArr[5] + "" + bArr[6] + "" + bArr[3] + "" + bArr[4];
                    bindingTaobao(c);
                }
            }
            @Override
            public void onFailure(int code, String msg) {

                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(SetActivity.this, msg,
                                Toast.LENGTH_LONG).show();
                    }
                });
            }
        });
    }

    @Override
    protected void onResume() {
        super.onResume();
        if(!"0".equals(SPUtils.getStringData(this,"coded","0"))){
            getToken(SPUtils.getStringData(this,"coded","0"));
            SPUtils.saveStringData(this,"coded","0");
        }
    }

    //绑定淘宝账号
    private void bindingTaobao(String tb_uid) {
        String url = Constants.BINDING_TAOBAO;
        OkHttpClient okHttpClient = new OkHttpClient();
        RequestBody body = new FormBody.Builder().add("token", token).add("tb_uid", tb_uid).build();
        Request request = new Request.Builder().url(url).post(body).build();
        Call call = okHttpClient.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                e.printStackTrace();
            }

            @Override
            public void onResponse(Call call, okhttp3.Response response) throws IOException {
                String result = response.body().string();
                try {
                    JSONObject jsonObject = new JSONObject(result);
                    String code = jsonObject.getString("code");
                    if ("0".equals(code)) {
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
//                                Toast.makeText(SetActivity.this, "绑定淘宝账号成功",
//                                        Toast.LENGTH_LONG).show();
                                bingRld();
                                tvTb.setTag("1");
                                tvTb.setText("淘宝号解绑");
                            }
                        });
                    } else {
                        Toast.makeText(SetActivity.this, "绑定淘宝账号失败",
                                Toast.LENGTH_LONG).show();
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }

            }
        });
    }
    private void bingRld(){
        openActivity(WebViewActivity4.class);
//        Intent intent = new Intent(this, WebViewActivity.class);
//        intent.putExtra("title","绑定淘宝分享渠道");
//        intent.putExtra("url","https://oauth.taobao.com/authorize?response_type=code&client_id="+Constants.qd_app_key+"&redirect_uri=http://127.0.0.1:12345/error&state=1212&view=wap");
//        startActivity(intent);
    }
    private void getToken(String code){
        String time=new SimpleDateFormat("yyy-MM-dd HH:mm:ss").format(new Date());
        RequestParams requestParams = new RequestParams();
        requestParams.put("method","taobao.top.auth.token.create");
        requestParams.put("app_key",Constants.qd_app_key);
        requestParams.put("format","json");
        requestParams.put("code",code);
        requestParams.put("timestamp",time);
        requestParams.put("v","2.0");
        requestParams.put("sign_method","md5");
        Map<String,String> temp=new HashMap<>();
        temp.put("method","taobao.top.auth.token.create");
        temp.put("app_key",Constants.qd_app_key);
        temp.put("format","json");
        temp.put("code",code);
        temp.put("timestamp",time);
        temp.put("v","2.0");
        temp.put("sign_method","md5");
        String sign= null;
        sign = PddClient.getSign3(temp,Constants.qd_app_secret);
        requestParams.put("sign",sign);
        HttpUtils.post1("https://eco.taobao.com/router/rest", requestParams, new TextHttpResponseHandler() {
            @Override
            public void onStart() {
                super.onStart();
                showLoadingDialog();
            }

            @Override
            public void onFinish() {
                super.onFinish();
                closeLoadingDialog();
            }

            @Override
            public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
            }

            @Override
            public void onSuccess(int statusCode, Header[] headers, String responseString) {
                String temp=responseString.replaceAll("\\\\","");
                temp=temp.replace("\"{","{").replace("}\"","}");
                try {
                    JSONObject object=new JSONObject(temp);
                    object=object.getJSONObject("top_auth_token_create_response");
                    temp=object.getString("token_result");
                    object=new JSONObject(temp);
                    getTemp(object.getString("refresh_token"));
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });
    }
    private void getTemp(String key){
        String time=new SimpleDateFormat("yyy-MM-dd HH:mm:ss").format(new Date());
        RequestParams requestParams = new RequestParams();
        requestParams.put("method","taobao.tbk.sc.publisher.info.save");
        requestParams.put("app_key",Constants.qd_app_key);
        requestParams.put("format","json");
        requestParams.put("session",key);
        requestParams.put("inviter_code",Constants.qd_app_code);
        requestParams.put("timestamp",time);
        requestParams.put("info_type","1");
        requestParams.put("v","2.0");
        requestParams.put("sign_method","md5");
        Map<String,String> temp=new HashMap<>();
        temp.put("method","taobao.tbk.sc.publisher.info.save");
        temp.put("app_key",Constants.qd_app_key);
        temp.put("format","json");
        temp.put("inviter_code",Constants.qd_app_code);
        temp.put("session",key);
        temp.put("info_type","1");
        temp.put("timestamp",time);
        temp.put("v","2.0");
        temp.put("sign_method","md5");
        String sign= null;
        sign = PddClient.getSign3(temp,Constants.qd_app_secret);
        requestParams.put("sign",sign);
        HttpUtils.post1("https://eco.taobao.com/router/rest", requestParams, new TextHttpResponseHandler() {
            @Override
            public void onStart() {
                super.onStart();
                showLoadingDialog();
            }

            @Override
            public void onFinish() {
                super.onFinish();
                closeLoadingDialog();
            }

            @Override
            public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
            }

            @Override
            public void onSuccess(int statusCode, Header[] headers, String responseString) {
                if(!responseString.contains("error_response")){
                    try {
                        JSONObject object=new JSONObject(responseString);
                        bindLd(object.getJSONObject("tbk_sc_publisher_info_save_response").getJSONObject("data").getString("relation_id"));
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }else{
                    ToastUtils.showShortToast(SetActivity.this,"绑定失败");
                }
            }
        });
    }
    private void unbindLd(){
        RequestParams params = new RequestParams();
        HttpUtils.post(Constants.UNBIND_RELATION_ID, params, new AsyncHttpResponseHandler() {
            @Override
            public void onStart() {
                super.onStart();
                showLoadingDialog();
            }

            @Override
            public void onSuccess(int arg0, Header[] arg1, byte[] arg2) {
                String responseResult = new String(arg2);
                try {
                    JSONObject jsonObject = new JSONObject(responseResult);
                    String code = jsonObject.optString("code");
                    String msg = jsonObject.optString("msg");
                    // String result = jsonObject.optString("result");
                    if ("0".equalsIgnoreCase(code)) { // 操作成功
//                        showToast("解除绑定成功");
                    } else {
                        showToast(msg);
                    }
                } catch (JSONException e) {
                    LogUtils.i(TAG, e.toString());
                }
            }

            @Override
            public void onFinish() {
                // 隐藏进度条
                super.onFinish();
                closeLoadingDialog();
            }

            @Override
            public void onFailure(int arg0, Header[] arg1, byte[] arg2, Throwable arg3) {
            }
        });
    }
    private void bindLd(String relation_id){
        RequestParams params = new RequestParams();
        params.put("tb_rid", relation_id);
        HttpUtils.post(Constants.BIND_RELATION_ID, params, new AsyncHttpResponseHandler() {
            @Override
            public void onStart() {
                super.onStart();
                showLoadingDialog();
            }

            @Override
            public void onSuccess(int arg0, Header[] arg1, byte[] arg2) {
                String responseResult = new String(arg2);
                LogUtils.e(TAG, "onSuccess()--" + responseResult);
                try {
                    JSONObject jsonObject = new JSONObject(responseResult);
                    String code = jsonObject.optString("code");
                    String msg = jsonObject.optString("msg");
                    // String result = jsonObject.optString("result");
                    if ("0".equalsIgnoreCase(code)) { // 操作成功
                        showToast("开通绑定成功");
                    } else {
                        showToast(msg);
                    }
                } catch (JSONException e) {
                    LogUtils.i(TAG, e.toString());
                }
            }

            @Override
            public void onFinish() {
                // 隐藏进度条
                super.onFinish();
                closeLoadingDialog();
            }

            @Override
            public void onFailure(int arg0, Header[] arg1, byte[] arg2, Throwable arg3) {
            }
        });
    }
    /**
     * @属性:清除缓存对话框
     * @开发者:陈飞
     * @时间:2018/7/28 23:37
     */
    public void showClearDialog() throws Exception {

        if (mMaterialDialog == null) {
            mMaterialDialog = new MaterialDialog(getComeActivity());//实例化对话框
        }
        mMaterialDialog.setTitle("清理缓存")
                .setMessage(Html.fromHtml("<p>当前缓存为" + CleanMessageUtil.getTotalCacheSize(getComeActivity()) + "<br>确认要清除缓存吗？</p>"))
                .setPositiveButton("是", new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        CleanMessageUtil.clearAllCache(getComeActivity());

//                        AccPass user;
//                        user = new AccPass();
//                        List<Object> listBean=new ArrayList<>();
//                        listBean.add(user);
//                        dataSave.setDataList("javaBean",listBean);

                        showToast("清除成功");
                        mMaterialDialog.dismiss();
                    }
                }).setNegativeButton("否", new View.OnClickListener() {

            @Override
            public void onClick(View view) {
                if (null != mMaterialDialog) {
                    mMaterialDialog.dismiss();
                }
            }
        })
                .setCanceledOnTouchOutside(true)
                .setOnDismissListener(
                        new DialogInterface.OnDismissListener() {
                            @Override
                            public void onDismiss(DialogInterface dialog) {
                                mMaterialDialog = null;
                            }
                        })
                .show();
    }

    /**
     * @属性:获取版本信息
     * @开发者:陈飞
     * @时间:2018/7/21 17:14
     */
    private void ArticleRequest() {
        RequestParams requestParams = new RequestParams();
        HttpUtils.post(Constants.MESSAGE_ARTICLE_VERSION_URL, requestParams, new onOKJsonHttpResponseHandler<VersionInformationBean>(new TypeToken<Response<VersionInformationBean>>() {
        }) {
            @Override
            public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
                showToast(responseString);
            }

            @Override
            public void onStart() {
                super.onStart();
                showLoadingDialog();
            }

            @Override
            public void onFinish() {
                super.onFinish();
                closeLoadingDialog();
            }

            @Override
            public void onSuccess(int statusCode, Response<VersionInformationBean> datas) {
                if (datas.isSuccess()) {
                    final VersionInformationBean data = datas.getData();

                    if (data != null) {
                        //对比当前版本
                        if (CommonUtils.compareVersion(APKVersionCodeUtils.getVerName(getComeActivity()), data.getVersion()) == -1) {
                            showTipDialog("发现新版本", data.getContent(), new onClickListener() {
                                @Override
                                public void onClickSure() {
                                    builder = UpdateService.Builder.create(data.getDown_android()).build(getComeActivity());
                                    downDilog.show();
                                    isDownLoadFinish = false;
                                    new Thread(new MyThread()).start();
                                }
                            }, null);
                        } else {
                            showTipDialog("版本信息", Html.fromHtml("当前版本已经是最新版啦<br>版本号：" + data.getVersion() + "</b>"));

                        }
                    }

                } else {
                    showToast(datas.getMsg());
                }
            }
        });
    }

    Handler handler = new Handler() {
        public void handleMessage(Message msg) {
            // 要做的事情
            downProgressBar.setProgress(builder.getUpdateProgress());
            if (builder.getUpdateProgress() >= 99) {
                isDownLoadFinish = true;
                UpdateService.Builder.updateProgress = 1;
                downDilog.dismiss();
            }
            if (builder.getUpdateProgress() == -1) {
                UpdateService.Builder.updateProgress = 1;
                downDilog.dismiss();
                isDownLoadFinish = true;
                T.showShort(getComeActivity(), "下载更新失败");
            }
            super.handleMessage(msg);
        }
    };

    @Override
    protected void onPause() {
        super.onPause();
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
    }

    public class MyThread implements Runnable {
        @Override
        public void run() {
            while (!isDownLoadFinish) {
                try {
                    Thread.sleep(500);
                    Message message = new Message();
                    message.what = 1;
                    handler.sendMessage(message);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    /**
     * 退出登录
     */
    private void getData() {
        if (!CommonUtils.isNetworkAvailable()) {
            showToast(getResources().getString(R.string.error_network));
            return;
        }
        RequestParams params = new RequestParams();
        params.put("token", token);
        HttpUtils.post(Constants.LOGIN_OUT, params, new TextHttpResponseHandler() {
            @Override
            public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
                // 输出错误信息
                LogUtils.e(TAG, "onFailure()--" + responseString);
            }

            @Override
            public void onFinish() {
                // 隐藏进度条
                super.onFinish();
                closeLoadingDialog();
            }

            @Override
            public void onSuccess(int statusCode, Header[] headers, String responseString) {
                try {
                    JSONObject jsonObject = new JSONObject(responseString);
                    //返回码
                    int code = jsonObject.optInt("code");
                    //返回码说明
                    String msg = jsonObject.optString("msg");
                    if (mAcache != null) {
                        if (0 == code) {
                            mAcache.put(Constants.TOKEN, "");
                            mAcache.put(Constants.GROUP_ID, "");
                            mAcache.put(Constants.ACCOUT, "");
                            mAcache.put(Constants.PASSWORD, "");
                            SPUtils.saveStringData(getComeActivity(), Constants.TOKEN, "");
//                        showToast(msg);

                        } else {
//                        showToast(msg);
                            mAcache.put(Constants.TOKEN, "");
                            mAcache.put(Constants.GROUP_ID, "");
                            mAcache.put(Constants.ACCOUT, "");
                            mAcache.put(Constants.PASSWORD, "");
                            SPUtils.saveStringData(getComeActivity(), Constants.TOKEN, "");

                        }
                    }
                    openActivity(WelActivity.class);
                    finish();
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onStart() {
                // 显示进度条
                super.onStart();
                showLoadingDialog();
            }
        });

    }

    /**
     * 设置登录用户名
     */
    private void setUsername() {
        if (!CommonUtils.isNetworkAvailable()) {
            showToast(getResources().getString(R.string.error_network));
            return;
        }
        if("".equals(logingName.getText().toString().trim())){
            showToast("请输入会员名");
            return;
        }
        RequestParams params = new RequestParams();
        params.put("token", token);
        params.put("username", logingName.getText().toString().trim());
        HttpUtils.post(Constants.SET_USERNAME, params, new TextHttpResponseHandler() {
            @Override
            public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
                // 输出错误信息
                LogUtils.e(TAG, "onFailure()--" + responseString);
            }

            @Override
            public void onFinish() {
                // 隐藏进度条
                super.onFinish();
                closeLoadingDialog();
            }

            @Override
            public void onSuccess(int statusCode, Header[] headers, String responseString) {
                try {
                    JSONObject jsonObject = new JSONObject(responseString);
                    //返回码
                    int code = jsonObject.optInt("code");
                    //返回码说明
                    String msg = jsonObject.optString("msg");
                    String data = jsonObject.optString("data");
                    showToast(msg);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onStart() {
                // 显示进度条
                super.onStart();
                showLoadingDialog();
            }
        });

    }

    /**
     * 获取用户信息
     */
    private void getUserMsg() {
        if (!CommonUtils.isNetworkAvailable()) {
            showToast(getResources().getString(R.string.error_network));
            return;
        }
        RequestParams params = new RequestParams();
        params.put("token", token);
        HttpUtils.post(Constants.GET_USER_MSG, params, new TextHttpResponseHandler() {
            @Override
            public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
                // 输出错误信息
                LogUtils.e(TAG, "onFailure()--" + responseString);
            }

            @Override
            public void onFinish() {
                // 隐藏进度条
                super.onFinish();
                closeLoadingDialog();
            }

            @Override
            public void onSuccess(int statusCode, Header[] headers, String responseString) {
                LogUtils.e(TAG, "onSuccess()--" + responseString);
                try {
                    JSONObject jsonObject = new JSONObject(responseString);
                    //返回码
                    int code = jsonObject.optInt("code");
                    //返回码说明
                    String msg = jsonObject.optString("msg");
                    String data = jsonObject.optString("data");
                    if (0 == code) {
                        if (!TextUtils.isEmpty(data)) {//GSON对数字都当做double解析
                            Gson gson = new Gson();
                            userBean = gson.fromJson(data.trim(), UserInfoBean.class);
                        }
                        logingName.setText(TypeConvertUtil.getString(userBean.user_msg.username, ""));//用户名
                        if(logingName.getText().toString()!=null&&!"".equals(logingName.getText().toString())){
                            logingName.setEnabled(false);
                            logingName.setClickable(false);
                            finishEdit.setVisibility(View.GONE);
                        }else{
                            finishEdit.setVisibility(View.VISIBLE);
                        }

                    } else {
                        showToast(msg);
                    }
                    getmerchantlist();
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onStart() {
                // 显示进度条
                super.onStart();
                showLoadingDialog();
            }
        });

    }

}
